<template>
  <div class="map-wrapper">
    <div ref="mapRef" class="map-container"></div>
    <div class="back-btn" v-if="currentArea !== '重庆市'" @click="backToCity">
      返回重庆市
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import * as echarts from "echarts";
import cityMap from "./data/chongqing.json";

// 自定义防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 基础样式配置
const baseStyle = {
  // 地图边框宽度
  borderWidth: 3,
  // 地图背景色
  backgroundColor: "transparent",
};

// 鼠标悬停样式配置
const hoverStyle = {
  label: {
    color: "#fff",
    fontSize: 16,
  },
  itemStyle: {
    areaColor: "#0160AD",
    borderWidth: baseStyle.borderWidth,
    borderType: "solid",
  },
};

// 风险等级颜色配置
const riskColors = {
  1: "rgb(134,48,75)", // 很高风险 - 红色
  2: "#ff6600", // 高风险 - 橙色
  3: "rgb(125,161,110)", // 中风险 - 黄色
  4: "rgb(37,112,183)", // 低风险 - 蓝色
  5: "rgb(49,122,101)", // 很低风险 - 绿色
};

// 边框颜色配置 - 比主色更亮
const riskBorderColors = {
  1: "rgb(213,70,112)", // 更亮的红色
  2: "#ffb366", // 更亮的橙色
  3: "rgb(211,218,56)", // 更亮的黄色
  4: "rgb(63,162,247)", // 更亮的蓝色
  5: "rgb(77,172,126)", // 更亮的绿色
};

// 标题样式配置
const titleStyle = {
  left: "center",
  textStyle: {
    color: "#fff",
    fontSize: 18,
    fontWeight: "normal",
  },
};

// 图例配置
const visualMapConfig = {
  type: "piecewise",
  left: "left",
  top: "bottom",
  itemWidth: 15,
  itemHeight: 10,
  textStyle: {
    color: "#fff",
    fontSize: 12,
  },
  pieces: [
    { gte: 90, label: "风险≥90", color: riskColors[5] },
    { gte: 80, lt: 90, label: "80≤风险<90", color: riskColors[4] },
    { gte: 70, lt: 80, label: "70≤风险<80", color: riskColors[3] },
    { gte: 60, lt: 70, label: "60≤风险<70", color: riskColors[2] },
    { lt: 60, label: "风险<60", color: riskColors[1] },
  ],
  selectedMode: "multiple",
  seriesIndex: 0,
  animation: false,
  realtime: true,
  calculable: false,
};

// 地图基础配置
const getCommonMapOptions = (name) => ({
  type: "map",
  map: name,
  roam: true,
  zoom: 1.2,
  scaleLimit: {
    min: 1,
    max: 5,
  },
  selectedMode: false,
  animation: false,
  animationDurationUpdate: 0,
  label: {
    show: true,
    fontSize: 10,
  },
  itemStyle: {
    borderWidth: baseStyle.borderWidth,
    borderType: "solid",
    shadowBlur: 0,
  },
  emphasis: hoverStyle,
});

// 处理地图数据的函数
const processMapData = (data) => {
  return data.map((item) => {
    // 根据风险确定对应的风险等级（1-5）
    let riskLevel;
    if (item.value >= 90) riskLevel = 5;
    else if (item.value >= 80) riskLevel = 4;
    else if (item.value >= 70) riskLevel = 3;
    else if (item.value >= 60) riskLevel = 2;
    else riskLevel = 1;

    return {
      name: item.name,
      value: item.value,
      itemStyle: {
        areaColor: riskColors[riskLevel],
        borderWidth: baseStyle.borderWidth,
        borderColor: riskBorderColors[riskLevel],
        borderType: "solid",
        shadowBlur: 0,
      },
      emphasis: {
        ...hoverStyle,
        itemStyle: {
          ...hoverStyle.itemStyle,
          borderColor: riskBorderColors[riskLevel],
        },
      },
    };
  });
};

const mapRef = ref(null);
const myChart = ref(null);
const currentArea = ref("重庆市");

// 区县中英文名映射表 - 用于加载对应的地图JSON文件
const districtNameMap = {
  涪陵区: "fuling",
  黔江区: "qianjiang",
  巴南区: "banan",
  万州区: "wanzhou",
  渝北区: "yubei",
  忠县: "zhongxian",
  云阳县: "yunyang",
  巫山县: "wushan",
  渝中区: "yuzhong",
  江北区: "jiangbei",
  南岸区: "nanan",
  九龙坡区: "jiulongpo",
  沙坪坝区: "shapingba",
  大渡口区: "dadukou",
  北碚区: "beibei",
  长寿区: "changshou",
  江津区: "jiangjin",
  合川区: "hechuan",
  永川区: "yongchuan",
  南川区: "nanchuan",
  綦江区: "qijiang",
  大足区: "dazu",
  璧山区: "bishan",
  铜梁区: "tongliang",
  潼南区: "tongnan",
  荣昌区: "rongchang",
  开州区: "kaizhou",
  梁平区: "liangping",
  武隆区: "wulong",
  城口县: "chengkou",
  丰都县: "fengdu",
  垫江县: "dianjiang",
  奉节县: "fengjie",
  巫溪县: "wuxi",
  石柱土家族自治县: "shizhu",
  秀山土家族苗族自治县: "xiushan",
  酉阳土家族苗族自治县: "youyang",
  彭水苗族土家族自治县: "pengshui",
};

// 区县地图数据缓存 - 避免重复加载相同的地图数据
const districtMapCache = new Map();

// 获取风险等级描述 - 根据风险值返回对应的文本和颜色
const getRiskLevel = (value) => {
  if (typeof value === "undefined" || value === null) {
    return { text: "暂无数据", color: "#999" };
  }
  if (value >= 90) return { text: "风险≥90", color: riskColors[5] };
  if (value >= 80) return { text: "80≤风险<90", color: riskColors[4] };
  if (value >= 70) return { text: "70≤风险<80", color: riskColors[3] };
  if (value >= 60) return { text: "60≤风险<70", color: riskColors[2] };
  return { text: "风险<60", color: riskColors[1] };
};

// 区域数据配置 - 包含所有区县的风险数据
const areaData = {
  重庆市: [
    // 红色区域（风险<60）
    { name: "长寿区", value: 55 },
    { name: "涪陵区", value: 55 },
    { name: "武隆区", value: 55 },
    { name: "璧山区", value: 55 },
    { name: "永川区", value: 55 },
    { name: "荣昌区", value: 55 },

    // 黄色区域（70≤风险<80）
    { name: "垫江县", value: 75 },

    // 蓝色区域（80≤风险<90）
    { name: "忠县", value: 85 },
    { name: "南川区", value: 85 },
    { name: "潼南区", value: 85 },

    // 其他区域为绿色（风险≥90）
    { name: "渝中区", value: 95 },
    { name: "江北区", value: 95 },
    { name: "南岸区", value: 95 },
    { name: "九龙坡区", value: 95 },
    { name: "沙坪坝区", value: 95 },
    { name: "大渡口区", value: 95 },
    { name: "渝北区", value: 95 },
    { name: "巴南区", value: 95 },
    { name: "北碚区", value: 95 },
    { name: "万州区", value: 95 },
    { name: "黔江区", value: 95 },
    { name: "江津区", value: 95 },
    { name: "合川区", value: 95 },
    { name: "綦江区", value: 95 },
    { name: "大足区", value: 95 },
    { name: "铜梁区", value: 95 },
    { name: "开州区", value: 95 },
    { name: "梁平区", value: 95 },
    { name: "城口县", value: 95 },
    { name: "丰都县", value: 95 },
    { name: "云阳县", value: 95 },
    { name: "奉节县", value: 95 },
    { name: "巫山县", value: 95 },
    { name: "巫溪县", value: 95 },
    { name: "石柱土家族自治县", value: 95 },
    { name: "秀山土家族苗族自治县", value: 95 },
    { name: "酉阳土家族苗族自治县", value: 95 },
    { name: "彭水苗族土家族自治县", value: 95 },
  ],
};

// 初始化地图函数
const initMap = () => {
  if (!mapRef.value) return;

  myChart.value = echarts.init(mapRef.value);
  echarts.registerMap("重庆", cityMap);

  // 使用已定义的 processMapData 函数处理数据
  const processedData = processMapData(areaData["重庆市"]);

  const option = {
    backgroundColor: baseStyle.backgroundColor,
    title: {
      text: `${currentArea.value}风险等级分布图`,
      ...titleStyle,
    },
    tooltip: {
      trigger: "item",
      backgroundColor: "rgba(0,0,0,0.8)",
      borderColor: "rgba(255,255,255,0.2)",
      borderWidth: 1,
      padding: [10, 15],
      textStyle: {
        color: "#fff",
        fontSize: 14,
      },
      formatter: (params) => {
        if (typeof params.value === "undefined" || params.value === null) {
          return `<div style="padding: 3px">
            <div style="font-size: 14px;color:#fff">${params.name}</div>
            <div style="font-size: 13px;color:#ccc">暂无数据</div>
          </div>`;
        }

        const risk = getRiskLevel(params.value);
        return `
          <div style="padding: 3px">
            <div style="font-size: 14px;color:#fff">${params.name}</div>
            <div style="font-size: 13px;color:#ccc">风险等级：${risk.text}</div>
            <div style="font-size: 13px;color:#ccc">风险值：${params.value}</div>
          </div>
        `;
      },
    },
    visualMap: visualMapConfig,
    series: [
      {
        ...getCommonMapOptions("重庆"),
        name: currentArea.value,
        data: processedData,
        selectedMode: false,
        itemStyle: {
          borderWidth: baseStyle.borderWidth,
          borderType: "solid",
          shadowBlur: 0,
        },
        emphasis: hoverStyle,
        select: {
          itemStyle: {
            areaColor: "#0160AD",
          },
        },
      },
    ],
  };

  myChart.value.setOption(option, true);

  // 注册事件监听
  myChart.value.on("click", handleMapClick);
  myChart.value.getZr().on("click", (params) => {
    if (params.target === undefined && currentArea.value !== "重庆市") {
      backToCity();
    }
  });

  // 强制刷新一次，确保所有区域的样式都被正确应用
  requestAnimationFrame(() => {
    myChart.value.setOption(
      {
        series: [
          {
            data: processedData,
          },
        ],
      },
      false
    );
  });
};

// 处理地图点击事件
const handleMapClick = async (params) => {
  if (currentArea.value === "重庆市") {
    try {
      const districtEnName = districtNameMap[params.name];
      if (!districtEnName) {
        console.error(`未找到 ${params.name} 对应的英文名`);
        return;
      }

      // 从缓存加载或异步加载地图数据
      let districtData;
      if (districtMapCache.has(districtEnName)) {
        districtData = districtMapCache.get(districtEnName);
      } else {
        districtData = await import(
          `./data/ChongqingCountyData/${districtEnName}.json`
        );
        districtMapCache.set(districtEnName, districtData);
      }

      // 更新当前区域并注册新地图
      currentArea.value = params.name;
      echarts.registerMap(params.name, districtData.default);

      // 获取区域数据
      const areaItem = areaData["重庆市"].find(
        (item) => item.name === params.name
      );

      // 计算风险等级
      let riskLevel;
      if (areaItem?.value >= 90) riskLevel = 5;
      else if (areaItem?.value >= 80) riskLevel = 4;
      else if (areaItem?.value >= 70) riskLevel = 3;
      else if (areaItem?.value >= 60) riskLevel = 2;
      else riskLevel = 1;

      // 更新地图配置
      const option = {
        tooltip: {
          trigger: "item",
          backgroundColor: "rgba(0,0,0,0.8)",
          borderColor: "rgba(255,255,255,0.2)",
          borderWidth: 1,
          padding: [10, 15],
          textStyle: {
            color: "#fff",
            fontSize: 14,
          },
          formatter: (params) => {
            if (typeof params.value === "undefined" || params.value === null) {
              return `<div style="padding: 3px">
                <div style="font-size: 14px;color:#fff">${params.name}</div>
                <div style="font-size: 13px;color:#ccc">暂无数据</div>
              </div>`;
            }

            const risk = getRiskLevel(params.value);
            return `
              <div style="padding: 3px">
                <div style="font-size: 14px;color:#fff">${params.name}</div>
                <div style="font-size: 13px;color:#ccc">风险等级：${risk.text}</div>
                <div style="font-size: 13px;color:#ccc">风险值：${params.value}</div>
              </div>
            `;
          },
        },
        series: [
          {
            name: params.name,
            type: "map",
            map: params.name,
            roam: true,
            zoom: 1.2,
            scaleLimit: {
              min: 1,
              max: 5,
            },
            selectedMode: false,
            animation: false,
            animationDurationUpdate: 0,
            data: [
              {
                name: params.name,
                value: areaItem?.value || 0,
                itemStyle: {
                  areaColor: riskColors[riskLevel],
                  borderWidth: baseStyle.borderWidth,
                  borderColor: riskBorderColors[riskLevel],
                  borderType: "solid",
                },
                emphasis: {
                  ...hoverStyle,
                  itemStyle: {
                    ...hoverStyle.itemStyle,
                    borderColor: riskBorderColors[riskLevel],
                  },
                },
              },
            ],
            label: {
              show: true,
              fontSize: 10,
            },
            itemStyle: {
              borderWidth: baseStyle.borderWidth,
              borderType: "solid",
            },
            emphasis: {
              ...hoverStyle,
              itemStyle: {
                ...hoverStyle.itemStyle,
                borderColor: riskBorderColors[riskLevel],
              },
            },
          },
        ],
        title: {
          text: `${params.name}风险等级分布图`,
        },
      };

      // 强制立即渲染
      myChart.value.setOption(option, true);
    } catch (error) {
      console.error("加载区县数据失败：", error);
    }
  }
};

// 使用防抖处理窗口resize事件
const handleResize = debounce(() => {
  myChart.value?.resize();
}, 200);

// 返回重庆市地图函数
const backToCity = () => {
  if (currentArea.value === "重庆市") return;

  currentArea.value = "重庆市";

  // 使用已定义的 processMapData 函数处理数据
  const processedData = processMapData(areaData["重庆市"]);

  const option = {
    backgroundColor: baseStyle.backgroundColor,
    title: {
      text: "重庆市风险等级分布图",
      ...titleStyle,
    },
    tooltip: {
      trigger: "item",
      backgroundColor: "rgba(0,0,0,0.8)",
      borderColor: "rgba(255,255,255,0.2)",
      borderWidth: 1,
      padding: [10, 15],
      textStyle: {
        color: "#fff",
        fontSize: 14,
      },
      formatter: (params) => {
        if (typeof params.value === "undefined" || params.value === null) {
          return `<div style="padding: 3px">
            <div style="font-size: 14px;color:#fff">${params.name}</div>
            <div style="font-size: 13px;color:#ccc">暂无数据</div>
          </div>`;
        }

        const risk = getRiskLevel(params.value);
        return `
          <div style="padding: 3px">
            <div style="font-size: 14px;color:#fff">${params.name}</div>
            <div style="font-size: 13px;color:#ccc">风险等级：${risk.text}</div>
            <div style="font-size: 13px;color:#ccc">风险值：${params.value}</div>
          </div>
        `;
      },
    },
    visualMap: visualMapConfig,
    series: [
      {
        ...getCommonMapOptions("重庆"),
        data: processedData,
      },
    ],
  };

  myChart.value.setOption(option, false);
};

onMounted(() => {
  initMap();
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  myChart.value?.dispose();
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped>
.map-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}

.map-container {
  width: 100%;
  height: 100%;
}

.back-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 8px 16px;
  background: rgba(0, 28, 64, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  color: #fff;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  z-index: 100;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: rgba(0, 28, 64, 0.9);
  border-color: rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
</style>
